//
//  MenuViewController.m
//  MeiLiProductModel
//
//  Created by B505 on 15/2/21.
//  Copyright (c) 2015年 孙晓林. All rights reserved.
//

#import "MenuViewController.h"
#import "SliderViewController.h"
#import "ExhibitionViewController.h"
#import "ActivityViewController.h"
#import "UIButton+Utils.h"
#import "T4Marco.h"

//%%% customizeable button attributes
#define X_BUFFER 0 //%%% the number of pixels on either side of the segment
#define Y_BUFFER 10 //%%% number of pixels on top of the segment
#define HEIGHT 30 //%%% height of the segment
// thickness of the selector bar
#define SELECTOR_WIDTH 80
#define SELECTOR_HEIGHT 3
#define X_OFFSET 8
#define INDEX_BUTTON_WIDTH 96
#define NAVIGATIONVIEW_WIDTH 196
#define NAVBAR_HEIGHT 44

#define MENU_BTN_X 12
#define MENU_BTN_Y 23

@interface MenuViewController ()<UIPageViewControllerDataSource, UIPageViewControllerDelegate, UIScrollViewDelegate>
{
    NSArray *viewControllerArray;
    UIScrollView *pageScrollView;
    NSInteger currentPageIndex;
}

@property (nonatomic, strong) UIView *selectionBar;
@property (nonatomic, strong)UIView *navigationView;
@property (nonatomic, strong)NSArray *buttonText;
@property (strong, nonatomic)UIView *navBar;


@end

@implementation MenuViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
     _pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
    _pageViewController.delegate = self;
    
    ExhibitionViewController *exhibitionVc = [[ExhibitionViewController alloc]init];
    ActivityViewController *activityVc = [[ActivityViewController alloc]init];
     _pageViewController.dataSource = self;
    viewControllerArray = @[exhibitionVc, activityVc];
    
    [self.pageViewController setViewControllers:@[viewControllerArray[0]] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil];
    
    [self addChildViewController:self.pageViewController];
    [self.view addSubview:self.pageViewController.view];
    
    CGRect pageViewRect = self.view.bounds;
    self.pageViewController.view.frame = pageViewRect;
    
    [self.pageViewController didMoveToParentViewController:self];
    self.view.gestureRecognizers = self.pageViewController.gestureRecognizers;
    
    
    _navBar = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, NAVBAR_HEIGHT)];
    _navBar.backgroundColor = [UIColor clearColor];
    UIButton *menuBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    menuBtn.frame = CGRectMake(MENU_BTN_X, MENU_BTN_Y, MENU_BUTTON_WIDTH, MENU_BUTTON_HEIGHT);
    [menuBtn setImageWithName:@"btn_menu"];
    [menuBtn addTarget:self action:@selector(onClickMenu:)];
    [_navBar addSubview:menuBtn];
    [self.view addSubview:_navBar];

    currentPageIndex = 0;
}

- (void)viewWillAppear:(BOOL)animated
{
    //用于防止滚动条重叠
    [_navigationView removeFromSuperview];
    
    [self syncScrollView];
    [self setupSegmentButtons];
    
}

- (void)onClickMenu:(UIButton *)btn
{
    T4_LOG_FUNC();
    [[SliderViewController sharedSliderController] showLeftViewController];
    
}

- (void)setupSegmentButtons
{
    _navigationView = [[UIView alloc]initWithFrame:CGRectMake(0,0, NAVIGATIONVIEW_WIDTH, HEIGHT)];
    
    NSInteger numControllers = [viewControllerArray count];
    
    if (!_buttonText) {
        _buttonText = [[NSArray alloc]initWithObjects: @"博物馆-展馆", @"展览-活动",nil]; //%%%buttontitle
    }
    
    for (int i = 0; i<numControllers; i++) {
        UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(X_BUFFER + i * INDEX_BUTTON_WIDTH, Y_BUFFER, INDEX_BUTTON_WIDTH - 6, HEIGHT)];
        [_navigationView addSubview:button];
        
        button.tag = i;
        //%%% IMPORTANT: if you make your own custom buttons, you have to tag them appropriately
        button.backgroundColor = [UIColor clearColor];//%%% buttoncolors
        
        [button addTarget:self action:@selector(tapSegmentButtonAction:)];
        button.titleFont = [UIFont systemFontOfSize:16];
        [button setTitle:[_buttonText objectAtIndex:i]];
    }
    
    _navigationView.center = _navBar.center;
    [_navBar addSubview:_navigationView];
    
    [self setupSelector];
}


//%%% sets up the selection bar under the buttons on the navigation bar
- (void)setupSelector
{
    _selectionBar = [[UIView alloc]initWithFrame:CGRectMake(5, 0, SELECTOR_WIDTH, SELECTOR_HEIGHT)];
    _selectionBar.backgroundColor = [UIColor whiteColor]; //%%% sbcolor
    _selectionBar.alpha = 1.0; //%%% sbalpha
    [_navigationView addSubview:_selectionBar];
}

- (void)syncScrollView
{
    for (UIView* view in _pageViewController.view.subviews){
        if([view isKindOfClass:[UIScrollView class]])
        {
            pageScrollView = (UIScrollView *)view;
            pageScrollView.delegate = self;
        }
    }
}

-(void)tapSegmentButtonAction:(UIButton *)button
{
    NSInteger tempIndex = currentPageIndex;
    
    __weak typeof(self) weakSelf = self;
    
    //%%% check to see if you're going left -> right or right -> left
    if (button.tag > tempIndex) {
        
        //%%% scroll through all the objects between the two points
        for (int i = (int)tempIndex + 1; i <= button.tag; i ++) {
            [_pageViewController setViewControllers:@[[viewControllerArray objectAtIndex:i]] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:^(BOOL complete){
                
                //%%% if the action finishes scrolling (i.e. the user doesn't stop it in the middle),
                //then it updates the page that it's currently on
                if (complete) {
                    [weakSelf updateCurrentPageIndex:i];
                }
            }];
        }
    }
    
    //%%% this is the same thing but for going right -> left
    else if (button.tag < tempIndex) {
        for (int i = (int)tempIndex - 1; i >= button.tag; i --) {
            [_pageViewController setViewControllers:@[[viewControllerArray objectAtIndex:i]] direction:UIPageViewControllerNavigationDirectionReverse animated:YES completion:^(BOOL complete){
                if (complete) {
                    [weakSelf updateCurrentPageIndex:i];
                }
            }];
        }
    }
}

//%%% makes sure the nav bar is always aware of what page you're on
//in reference to the array of view controllers you gave
- (void)updateCurrentPageIndex:(int)newIndex
{
    currentPageIndex = newIndex;
}

//%%% method is called when any of the pages moves.
//It extracts the xcoordinate from the center point and instructs the selection bar to move accordingly
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat xFromCenter = self.view.frame.size.width - pageScrollView.contentOffset.x;

    //%%% positive for right swipe, negative for left
    
    //%%% checks to see what page you are on and adjusts the xCoor accordingly.
    //i.e. if you're on the second page, it makes sure that the bar starts from the frame.origin.x of the
    //second tab instead of the beginning
    NSInteger xCoor = X_BUFFER + _selectionBar.frame.size.width*currentPageIndex - X_OFFSET;
    int distance = (int)(xCoor - xFromCenter /[viewControllerArray count]) % 100;
    
    if (currentPageIndex == 1) {
        _selectionBar.frame = CGRectMake(distance + 28 , _selectionBar.frame.origin.y, _selectionBar.frame.size.width, _selectionBar.frame.size.height);
    }else
    {
    _selectionBar.frame = CGRectMake(distance + 15, _selectionBar.frame.origin.y, _selectionBar.frame.size.width, _selectionBar.frame.size.height);
    }
        NSLog(@"x = %f, 123 = %f",_selectionBar.frame.origin.x, xCoor - xFromCenter /[viewControllerArray count]);
}

#pragma mark - Page View Controller Data Source

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController
{
    NSInteger index = [self indexOfController:viewController];
    
    if ((index == NSNotFound) || (index == 0)) {
        return nil;
    }
    
    index --;
    return [viewControllerArray objectAtIndex:index];
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
{
    NSInteger index = [self indexOfController:viewController];
    
    if (index == NSNotFound) {
        return nil;
    }
    index++;
    
    if (index == [viewControllerArray count]) {
        return nil;
    }
    return [viewControllerArray objectAtIndex:index];
}

-(void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed
{
    if (completed) {
        currentPageIndex = [self indexOfController:[pageViewController.viewControllers lastObject]];
    }
}


//%%% checks to see which item we are currently looking at from the array of view controllers.
// not really a delegate method, but is used in all the delegate methods, so might as well include it here
-(NSInteger)indexOfController:(UIViewController *)viewController
{
    for (int i = 0; i<[viewControllerArray count]; i++) {
        if (viewController == [viewControllerArray objectAtIndex:i])
        {
            return i;
        }
    }
    return NSNotFound;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
